package com.example.demo.itext;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Text2PDF {
    public static void main(String[] args) {
        String inputTxtFile = "input.txt"; // 输入的txt文件路径
        String outputPdfFile = "output.pdf"; // 输出的pdf文件路径
        String encoding = "UTF-8"; // 假设txt文件使用的是UTF-8编码

        try {
            FileOutputStream fos = new FileOutputStream(outputPdfFile);
            Document document = new Document();
            PdfWriter.getInstance(document, fos);
            document.open();

            File file = new File(inputTxtFile);
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            String text = new String(b, encoding); // 使用正确的编码读取文本

            Paragraph paragraph = new Paragraph(text);
            document.add(paragraph);

            document.close();
            fis.close();
            fos.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}